// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/functions/sparksql/aggregates/bitwise_xor_aggregate.h>

#include <pollux/functions/lib/aggregates/bitwise_aggregate_base.h>

namespace kumo::pollux::functions::aggregate::sparksql {
    namespace {
        template<typename T>
        class BitwiseXorAggregate : public BitwiseAggregateBase<T> {
        public:
            explicit BitwiseXorAggregate(TypePtr resultType)
                : aggregate::BitwiseAggregateBase<T>(
                    resultType,
                    /* initialValue = */ 0) {
            }

            void addRawInput(
                char **groups,
                const SelectivityVector &rows,
                const std::vector<VectorPtr> &args,
                bool mayPushdown) override {
                aggregate::SimpleNumericAggregate<T, T, T>::template updateGroups<true>(
                    groups,
                    rows,
                    args[0],
                    [](T &result, T value) { result ^= value; },
                    mayPushdown);
            }

            void addSingleGroupRawInput(
                char *group,
                const SelectivityVector &rows,
                const std::vector<VectorPtr> &args,
                bool mayPushdown) override {
                aggregate::SimpleNumericAggregate<T, T, T>::updateOneGroup(
                    group,
                    rows,
                    args[0],
                    [](T &result, T value) { result ^= value; },
                    [](T &result, T value, int n) {
                        if ((n & 1) == 1) {
                            result ^= value;
                        }
                    },
                    mayPushdown,
                    this->initialValue_);
            }
        };
    } // namespace

    exec::AggregateRegistrationResult registerBitwiseXorAggregate(
        const std::string &prefix,
        bool withCompanionFunctions,
        bool overwrite) {
        return functions::aggregate::registerBitwise<BitwiseXorAggregate>(
            prefix + "bit_xor", withCompanionFunctions, false, overwrite);
    }
} // namespace kumo::pollux::functions::aggregate::sparksql
